﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Collections.Specialized;

namespace Duson.Controls.Pager
{
    [System.ComponentModel.Designer(typeof(PagerDesigner))]
    [ToolboxData(@"<{0}:Pager runat='server'></{0}:Pager>")]
    public class Pager : WebControl, INamingContainer, IPostBackEventHandler
    {
        #region 私有变量
        private PageMethodAbstract _pageMethod; // 分页方式
        private SkipTypeAbstract _skipType; // 页码跳转方式
        #endregion

        #region 属性
        /// <summary>
        /// 分页方式工厂
        /// </summary>
        private PageMethodAbstract PageMethodFactory
        {
            get
            {
                switch (PagingMethod)
                {
                    case PagingMethod.PostBack:
                        _pageMethod = new PageMethod_PostBack();
                        break;
                    case PagingMethod.Url:
                        _pageMethod = new PageMethod_Url();
                        break;
                }

                _pageMethod.MyPager = this;
                return _pageMethod;
            }

            set { _pageMethod = value; }
        }

        /// <summary>
        /// 页码跳转方式工厂
        /// </summary>
        private SkipTypeAbstract SkipTypeFactory
        {
            get
            {
                switch (PageIndexBoxType)
                {
                    case PageIndexBoxType.TextBox:
                        _skipType = new SkipType_TextBox();
                        break;
                    case PageIndexBoxType.DropDownList:
                        _skipType = new SkipType_DropDownList();
                        break;
                }

                _skipType.MyPager = this;
                return _skipType;
            }

            set { _skipType = value; }
        }
        #endregion

        #region 控件属性
        [Browsable(true),
        DefaultValue("首页"),
        Category("分页"),
        Description("")]
        public string FirstPageText
        {
            get { return ViewState["FirstPageText"] != null ? ViewState["FirstPageText"].ToString() : "首页"; }
            set { ViewState["FirstPageText"] = value; }
        }

        [Browsable(true),
        DefaultValue("上一页"),
        Category("分页"),
        Description("")]
        public string PrePageText
        {
            get { return ViewState["PrePageText"] != null ? ViewState["PrePageText"].ToString() : "上一页"; }
            set { ViewState["PrePageText"] = value; }
        }

        [Browsable(true),
        DefaultValue("下一页"),
        Category("分页"),
        Description("")]
        public string NextPageText
        {
            get { return ViewState["NextPageText"] != null ? ViewState["NextPageText"].ToString() : "下一页"; }
            set { ViewState["NextPageText"] = value; }
        }

        [Browsable(true),
        DefaultValue("尾页"),
        Category("分页"),
        Description("")]
        public string LastPageText
        {
            get { return ViewState["LastPageText"] != null ? ViewState["LastPageText"].ToString() : "尾页"; }
            set { ViewState["LastPageText"] = value; }
        }

        [Browsable(true),
        DefaultValue("go"),
        Category("分页"),
        Description("跳转按钮文本")]
        public string GoButtonText
        {
            get { return ViewState["GoButtonText"] != null ? ViewState["GoButtonText"].ToString() : "go"; }
            set { ViewState["GoButtonText"] = value; }
        }

        [Browsable(false),
        DefaultValue(1),
        Category("分页"),
        Description("当前页码")]
        public int PageIndex
        {
            get { return ViewState["PageIndex"] != null ? int.Parse(ViewState["PageIndex"].ToString()) : 1; }
            set { ViewState["PageIndex"] = value; }
        }

        [Browsable(true),
        DefaultValue(10),
        Category("分页"),
        Description("每页显示的条数")]
        public int PageSize
        {
            get { return ViewState["PageSize"] != null ? int.Parse(ViewState["PageSize"].ToString()) : 10; }
            set { ViewState["PageSize"] = value; }
        }

        [Browsable(false),
        DefaultValue(0),
        Category("分页"),
        Description("总记录数")]
        public int RecordCount
        {
            get { return ViewState["RecordCount"] != null ? int.Parse(ViewState["RecordCount"].ToString()) : 0; }
            set { ViewState["RecordCount"] = value; }
        }

        [Browsable(false),
        DefaultValue(0),
        Category("分页"),
        Description("总页数")]
        public int TotalPage
        {
            get
            {
                if (RecordCount == 0)
                    return 1;
                return (int)Math.Ceiling((double)RecordCount / (double)PageSize);

                // return (RecordCount - 1) / PageSize + 1;
            }
        }

        [Browsable(true),
        DefaultValue(10),
        Category("分页"),
        Description("导航的数量")]
        public int NavCount
        {
            get { return ViewState["NavCount"] != null ? int.Parse(ViewState["NavCount"].ToString()) : 10; }
            set { ViewState["NavCount"] = value; }
        }

        [Category("分页")]
        [Description("分页方式")]
        public PagingMethod PagingMethod
        {
            get { return ViewState["PagingMethod"] != null ? (PagingMethod)ViewState["PagingMethod"] : PagingMethod.PostBack; }
            set { ViewState["PagingMethod"] = value; }
        }

        [Category("分页")]
        [Description("跳转方式")]
        public PageIndexBoxType PageIndexBoxType
        {
            get { return ViewState["PageIndexBoxType"] != null ? (PageIndexBoxType)ViewState["PageIndexBoxType"] : PageIndexBoxType.TextBox; }
            set { ViewState["PageIndexBoxType"] = value; }
        }
        #endregion

        #region 事件
        private static readonly object eventPageChanging = new object();

        public event EventHandler PageChanging
        {
            add { Events.AddHandler(eventPageChanging, value); }
            remove { Events.RemoveHandler(eventPageChanging, value); }
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            int newPage;
            if (!int.TryParse(eventArgument, out newPage))
                return;

            if (newPage < 1)
                newPage = 1;
            if (newPage > TotalPage)
                newPage = TotalPage;

            PageIndex = newPage;

            OnPageChange(new EventArgs());
        }

        protected virtual void OnPageChange(EventArgs e)
        {
            EventHandler handler = (EventHandler)Events[eventPageChanging];
            if (handler != null)
                handler(this, e);
        }
        #endregion

        #region 输出内容
        protected override void OnPreRender(EventArgs e)
        {
            Type type = typeof(Pager);
            Page.ClientScript.RegisterClientScriptResource(type, "Duson.Controls.Pager.Js.Function.js");

            base.OnPreRender(e);
        }

        // 为Url分页用
        protected override void OnLoad(EventArgs e)
        {
            if (Page.Request[ConstParams.Url_Params] != null)
            {
                RaisePostBackEvent(Page.Request[ConstParams.Url_Params]);
            }

            base.OnLoad(e);
        }        
        protected override HtmlTextWriterTag TagKey        {
            get { return HtmlTextWriterTag.Div; }        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            // 页码信息
            writer.Write(GetPageString());

            // 页码跳转
            SkipTypeFactory.CreateControls(writer);
        }
        #endregion

        #region 私有函数
        /// <summary>
        /// 获得页码信息
        /// </summary>
        /// <returns></returns>
        protected string GetPageString()
        {
            StringBuilder sbPage = new StringBuilder();
            sbPage.Append(string.Format("每页{0}条&nbsp;共{1}条,第{2}/{3}页&nbsp;", PageSize, RecordCount, PageIndex, TotalPage));

            if (PageIndex == 1)
            {
                sbPage.Append(string.Format("{0}", FirstPageText));
                sbPage.Append(string.Format("  {0}", PrePageText));
            }
            else
            {
                sbPage.Append(GetHref(FirstPageText, 1));
                sbPage.Append(GetHref(PrePageText, PageIndex - 1));
            }

            sbPage.Append(GetNav());

            if (PageIndex == TotalPage || PageIndex == 0)
            {
                sbPage.Append(string.Format("{0}", NextPageText));
                sbPage.Append(string.Format("  {0}", LastPageText));
            }
            else
            {
                sbPage.Append(GetHref(NextPageText, PageIndex + 1));
                sbPage.Append(GetHref(LastPageText, TotalPage));
            }

            return sbPage.ToString();
        }

        /// <summary>
        /// 获得页码导航
        /// </summary>
        /// <returns></returns>
        protected string GetNav()
        {
            StringBuilder sbNav = new StringBuilder();

            int noCount = NavCount;
            if (TotalPage < NavCount)
                noCount = TotalPage;

            //int tmpMod = PageIndex % noCount;
            //if (tmpMod == 0)
            //    tmpMod = noCount;
            //int noStart = PageIndex - tmpMod;

            int noStart = ((PageIndex - 1) / noCount) * noCount;

            if (PageIndex > noCount)
            {
                sbNav.Append(GetHref("...", noStart));
            }

            int i;
            for (i = noStart + 1; i <= noStart + noCount; i++)
            {
                if (i == PageIndex)
                    sbNav.Append(string.Format("<font color='red'>{0}</font>  ", i));
                else
                    sbNav.Append(GetHref(i.ToString(), i));

                if (i >= TotalPage)
                {
                    return sbNav.ToString();
                }
            }

            if (i <= TotalPage)
            {
                sbNav.Append(GetHref("...", i));
            }

            return sbNav.ToString();
        }

        /// <summary>
        /// 构造页码分页方式
        /// </summary>
        /// <param name="text">显示文字</param>
        /// <param name="pageIndex">页码</param>
        /// <returns></returns>
        protected string GetHref(string text, int pageIndex)
        {
            return PageMethodFactory.GetHref(text, pageIndex);
        }
        #endregion

    }

}